package com.ccsoft.netty.websocket;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;

/**
 * @author chanchaw
 * @create 2022-07-19 13:11
 */
public class ServerInitializer extends ChannelInitializer<SocketChannel> {
    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {
        ChannelPipeline pipeline = socketChannel.pipeline();
        // websocket 是基于 http 所以首先要添加 http 编解码
        pipeline.addLast(new HttpServerCodec());
        // websocket 以块方式读写，要添加下面的 handler
        pipeline.addLast(new ChunkedWriteHandler());
        // http数据在传输过程中分段，使用 HttpObjectAggregator 将多个段聚合
        // 这样就是为什么当浏览器发送大量数据时，就会发出多次 http 请求
        pipeline.addLast(new HttpObjectAggregator(8192));
        // 浏览器请求 ws://localhost:7000/hello 其请求的 uri = /hello
        // 下面表示解析该 uri 的请求
        // WebSocketServerProtocolHandler的核心功能是将 http 协议升级为 ws 协议，保持长链接
        pipeline.addLast(new WebSocketServerProtocolHandler("/hello"));
        // 添加自定义的 handler
        pipeline.addLast(new ServerHandler());
    }
}
